package vashion.azeroth.core.manager.item;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;

import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.BrandErrorEnum;
import vashion.azeroth.contant.ForestErrorEnum;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.ItemErrorEnum;
import vashion.azeroth.core.common.NeedOperateFlow;
import vashion.azeroth.core.dao.BaseDao;
import vashion.azeroth.core.item.dao.ItemForestBrandDao;
import vashion.azeroth.core.item.pojo.ForestDO;
import vashion.azeroth.core.item.pojo.ItemBrandDO;
import vashion.azeroth.core.item.pojo.ItemForestBrandDO;
import vashion.azeroth.core.item.pojo.ItemForestBrandQueryDO;
import vashion.azeroth.core.manager.forest.BaseForestManager;
import vashion.azeroth.core.manager.impl.BaseManagerImpl;
import vashion.azeroth.core.pojo.common.OperateFlowEnum;
import vashion.azeroth.core.result.ApiResult;

/**
 * Created by Loki on 17/1/10. 基础的品类相关品牌管理
 */
@Service
public class BaseItemForestBrandManager extends BaseManagerImpl<ItemForestBrandDO> {
	private final static Logger log = LoggerFactory.getLogger(BaseItemForestBrandManager.class);

	@Autowired
	ItemForestBrandDao itemForestBrandDao;
	@Autowired
	BaseForestManager baseForestManager;
	@Autowired
	BaseItemBrandManager baseItemBrandManager;

	@Override
	public BaseDao<ItemForestBrandDO> getDao() {
		// TODO Auto-generated method stub
		return itemForestBrandDao;
	}

	/**
	 * 查询一种品类相关品牌
	 *
	 * @param itemBrandDO
	 * @return
	 */
	public ApiResult<List<ItemForestBrandDO>> getBrandListByForestId(ItemForestBrandDO itemForestBrandDO) {
		ApiResult<List<ItemForestBrandDO>> result = new ApiResult<List<ItemForestBrandDO>>();
		try {
			// 如果是二级类目，获取父类目对于的品牌
			ForestDO forest = baseForestManager.get(itemForestBrandDO.getForestId());
			if (null != forest && null != forest.getParentId() && forest.getParentId() > 0) {
				itemForestBrandDO.setForestId(forest.getParentId());
			}
			itemForestBrandDO.setStatus(AzerothConstants.ItemForestBrand.NORMAL);
			itemForestBrandDO.setPageSize(1000);
			List<ItemForestBrandDO> itemForestBrandList = (List<ItemForestBrandDO>) itemForestBrandDao.getBrandListByForestId(itemForestBrandDO);
			if (itemForestBrandList.size() == 0 || itemForestBrandList == null) {
				return ApiResult.newErrorResult(
						GenericErrorEnum.QUERY_NO_DATA.getErrorCode(),
						GenericErrorEnum.QUERY_NO_DATA.getErrorMessage());
			} else {
				//去重复
				List<ItemForestBrandDO> listWithoutDup = removeDuplicateBrand(itemForestBrandList);
				result = (ApiResult<List<ItemForestBrandDO>>) ApiResult.newSuccessResult(listWithoutDup);
				result.setTotalCount(listWithoutDup.size());
			}
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return (ApiResult<List<ItemForestBrandDO>>) result;
	}
	
	/**
	 * 查询多种品类相关品牌
	 *
	 * @param itemBrandDO
	 * @return
	 */
	public ApiResult<List<ItemForestBrandDO>> getBrandListByForestIds(String forestIds) {
		ApiResult<List<ItemForestBrandDO>> result = new ApiResult<List<ItemForestBrandDO>>();
		try {
			ItemForestBrandQueryDO itemForestBrandQueryDO = new ItemForestBrandQueryDO();
			//拆分forestIdList
			if (StringUtils.isNotEmpty(forestIds)) {
				String[] forestIdArray = forestIds.split(",");
			    List<Long> forestIdList = new ArrayList<Long>();  
			    for(String forestId : forestIdArray){  
			        Long listlong = Long.parseLong(forestId);  
			        forestIdList.add(listlong);
			        // 如果是二级类目，加入父类目对于的品牌
					ForestDO forest = baseForestManager.get(listlong);
					if (null != forest && null != forest.getParentId() && forest.getParentId() > 0) {
						forestIdList.add(forest.getParentId());
					}
			        //查找子类目的ID列表
			        List<ForestDO> childrenForestList = baseForestManager
			        						.getChildrenForestList(listlong).getData();
			        if (!CollectionUtils.isEmpty(childrenForestList)) {
			        	for (ForestDO childForest : childrenForestList) {
			        		forestIdList.add(childForest.getId());
			        	}
			        }
			    }
			    if (!forestIdList.isEmpty()) {
			    	itemForestBrandQueryDO.setForestIdList(new ArrayList<Long>(new HashSet<Long>(forestIdList)));
			    }
			}
			itemForestBrandQueryDO.setStatus(AzerothConstants.ItemForestBrand.NORMAL);
			itemForestBrandQueryDO.setPageSize(1000);
			List<ItemForestBrandDO> itemForestBrandList = (List<ItemForestBrandDO>) itemForestBrandDao
														.getBrandListByForestIds(itemForestBrandQueryDO);
			if (CollectionUtils.isEmpty(itemForestBrandList)) {
				return ApiResult.newErrorResult(
						GenericErrorEnum.QUERY_NO_DATA.getErrorCode(),
						GenericErrorEnum.QUERY_NO_DATA.getErrorMessage());
			} else {
				//去重复
				List<ItemForestBrandDO> listWithoutDup = removeDuplicateBrand(itemForestBrandList);
				result = (ApiResult<List<ItemForestBrandDO>>) ApiResult.newSuccessResult(listWithoutDup);
				result.setTotalCount(listWithoutDup.size());
			}
		} catch (NumberFormatException e) {
			return ApiResult.newErrorResult(ItemErrorEnum.CATEGORY_ID_ERROR.getErrorCode(), 
					ItemErrorEnum.CATEGORY_ID_ERROR.getErrorMessage());
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
			
		}
		return (ApiResult<List<ItemForestBrandDO>>) result;
	}
	
	/**
	 * 保存与一个品牌关联的多个类目的信息
	 * @param brandDO
	 * @param forestIds
	 * @return
	 */
    public ApiResult<Boolean> publishBrandForestIdList(ItemBrandDO brandDO, String forestIds, long operateId) {
		try {
			if (StringUtils.isNotEmpty(forestIds)) {
				String[] forestIdArray = forestIds.split(",");  
			    for(String forestId : forestIdArray){
			        Long listlong = Long.parseLong(forestId);
			        this.publishBrandForestId(brandDO, listlong, operateId);
			    }
			}
		}catch (NumberFormatException e) {
			return ApiResult.newErrorResult(ItemErrorEnum.CATEGORY_ID_ERROR.getErrorCode(), 
					ItemErrorEnum.CATEGORY_ID_ERROR.getErrorMessage());
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(true);
	}
	
	/**
	 * 保存一个类目与多个品牌关联的信息
	 * @param brandDO
	 * @param forestIds
	 * @return
	 */
    public ApiResult<Boolean> publishBrandIdListForest(String brandIds, ForestDO forestDO, long operateId) {
		try {
			if (StringUtils.isNotEmpty(brandIds)) {
				String[] brandIdArray = brandIds.split(",");  
			    for(String brandId : brandIdArray){
			        Long brandIdLong = Long.parseLong(brandId);
			        this.publishBrandIdForest(brandIdLong, forestDO, operateId);
			    }
			}
		}catch (NumberFormatException e) {
			return ApiResult.newErrorResult(ItemErrorEnum.CATEGORY_ID_ERROR.getErrorCode(), 
					ItemErrorEnum.CATEGORY_ID_ERROR.getErrorMessage());
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(true);
	}
	
	/**
	 * 保存与一个品牌关联的一个类目的信息
	 * @param brandDO
	 * @param forestId
	 * @return
	 */
    public ApiResult<Boolean> publishBrandForestId(ItemBrandDO brandDO, long forestId, long operateId) {
        //获取类目
		ForestDO dbForestDO = baseForestManager.get(forestId);
		//保存单个brand和forest关联
        return this.publishBrandForest(brandDO, dbForestDO, operateId);
	}
	
	/**
	 * 保存与一个品牌关联的一个类目的信息
	 * @param brandDO
	 * @param forestId
	 * @return
	 */
    public ApiResult<Boolean> publishBrandIdForest(long brandId, ForestDO forestDO, long operateId) {
        //获取品牌
		ItemBrandDO dbBrandDO = baseItemBrandManager.get(brandId);
		//保存单个brand和forest关联
        return this.publishBrandForest(dbBrandDO, forestDO, operateId);
	}
	
	/**
	 * 保存与一个品牌关联的一个类目的信息
	 * @param brandDO
	 * @param forestDO
	 * @return
	 */
	@NeedOperateFlow(operateIdArgLocation = 2, operateFlowEnum = OperateFlowEnum.BRAND)
    public ApiResult<Boolean> publishBrandForest(ItemBrandDO brandDO, ForestDO forestDO, long operateId) {
		
		//检查品牌是否存在
		if (null == brandDO || StringUtils.isBlank(brandDO.getTitle()) 
				|| AzerothConstants.ItemBrand.NORMAL != brandDO.getStatus()) {
            return ApiResult.newErrorResult(BrandErrorEnum.ARG_ERROR.getErrorCode(), BrandErrorEnum.ARG_ERROR.getErrorMessage());
        }
		
		//检查类目是否存在
        if (null == forestDO || StringUtils.isBlank(forestDO.getTitle()) 
				|| AzerothConstants.ItemForest.NORMAL != forestDO.getStatus()) {
            return ApiResult.newErrorResult(ForestErrorEnum.IS_NULL.getErrorCode(), ForestErrorEnum.IS_NULL.getErrorMessage());
        }
		ItemForestBrandDO itemForestBrandDO = new ItemForestBrandDO();
		itemForestBrandDO.setForestId(forestDO.getId());
		itemForestBrandDO.setBrandId(brandDO.getId());
		itemForestBrandDO.setStatus(AzerothConstants.ItemForestBrand.NORMAL);
		
        //检查品牌类目是否已关联
		List<ItemForestBrandDO> dbForestBrandList = this.find(itemForestBrandDO);
		if (!CollectionUtils.isEmpty(dbForestBrandList)) {
			return ApiResult.newErrorResult(BrandErrorEnum.ALREADY_CONNECT.getErrorCode(), 
					BrandErrorEnum.ALREADY_CONNECT.getErrorMessage());
		}
		
		//保存关联信息
		itemForestBrandDO.setBrandTitle(brandDO.getTitle());
		itemForestBrandDO.setGmtCreate(new Date());
		itemForestBrandDO.setGmtModified(new Date());
        try {
        	this.save(itemForestBrandDO);
        } catch (Exception e) {
            log.error("BaseBrandManager.publishBrand error, forestD=" + brandDO, e);
            return ApiResult.newErrorResult(ForestErrorEnum.SYSTEM_ERROR.getErrorCode(), ForestErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
        return ApiResult.newSuccessResult(true);
	}
	
	/**
	 * 更新一个类目与多个品牌关联的信息，不在brandIds中的删除
	 * @param brandDO
	 * @param forestIds
	 * @return
	 */
    public ApiResult<Boolean> updateBrandIdListForest(String brandIds, ForestDO forestDO, long operateId) {
		try {
			if (StringUtils.isNotEmpty(brandIds)) {
				if (forestDO.getId() >= 0) {
					//不在brandIds中的已关联商品删除
					ItemForestBrandDO itemForestBrandDO = new ItemForestBrandDO();
					itemForestBrandDO.setForestId(forestDO.getId());
					ApiResult<List<ItemForestBrandDO>> forestBrandResult = this.getBrandListByForestId(itemForestBrandDO);
					if (forestBrandResult.isSuccess()) {
						List<ItemForestBrandDO> forestBrandList = forestBrandResult.getData();
						for (ItemForestBrandDO forestBrand : forestBrandList) {
							if (!brandIds.contains(String.valueOf(forestBrand.getBrandId()))) {
								this.getDao().remove(forestBrand);
							}
						}
					}
				}
				String[] brandIdArray = brandIds.split(",");  
			    for(String brandId : brandIdArray){
			        Long brandIdLong = Long.parseLong(brandId);
			        this.publishBrandIdForest(brandIdLong, forestDO, operateId);
			    }
			}
		}catch (NumberFormatException e) {
			return ApiResult.newErrorResult(ItemErrorEnum.CATEGORY_ID_ERROR.getErrorCode(), 
					ItemErrorEnum.CATEGORY_ID_ERROR.getErrorMessage());
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(true);
	}
    
	
	/**
	 * 更新与一个品牌关联的多个类目的信息
	 * @param brandDO
	 * @param forestIds
	 * @return 更新的结果
	 */
    public ApiResult<Boolean> updateBrandForestIdList(ItemBrandDO brandDO, String forestIds, long operateId) {
    	try {
			if (StringUtils.isNotEmpty(forestIds)) {
				if (brandDO.getId() >= 0) {
					//不在forestIds中的已关联商品删除
					ItemForestBrandDO forestBrandQuery = new ItemForestBrandDO();
					forestBrandQuery.setBrandId(brandDO.getId());
					forestBrandQuery.setStatus(AzerothConstants.ItemForestBrand.NORMAL);
					List<ItemForestBrandDO> forestBrandList = this.find(forestBrandQuery);
					if (!CollectionUtils.isEmpty(forestBrandList)) {
						for (ItemForestBrandDO forestBrand : forestBrandList) {
							if (!forestIds.contains(String.valueOf(forestBrand.getForestId()))) {
								this.getDao().remove(forestBrand);
							}
						}
					}
				}
				String[] forestIdArray = forestIds.split(",");  
			    for(String forestId : forestIdArray){
			        Long forestIdLong = Long.parseLong(forestId);
			        this.publishBrandForestId(brandDO, forestIdLong, operateId);
			    }
			}
		}catch (NumberFormatException e) {
			return ApiResult.newErrorResult(ItemErrorEnum.CATEGORY_ID_ERROR.getErrorCode(), 
					ItemErrorEnum.CATEGORY_ID_ERROR.getErrorMessage());
		} catch (Exception e) {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(true);
    }

	/**
	 * 根据品牌的ID，查询出关联的类目
	 * @param brandId
	 * @return 关联的类目
	 */
	public List<ForestDO> getForestListByBrandId(long brandId) {
		ItemForestBrandDO forestBrandQuery = new ItemForestBrandDO();
		forestBrandQuery.setBrandId(brandId);
		forestBrandQuery.setStatus(AzerothConstants.ItemForestBrand.NORMAL);
		forestBrandQuery.setPageSize(1000);
		List<ItemForestBrandDO> forestBrandList = this.find(forestBrandQuery);
		List<ForestDO> forestList = Lists.<ForestDO>newArrayList();
		if (!CollectionUtils.isEmpty(forestBrandList)) {
			for (ItemForestBrandDO forestBrandTemp : forestBrandList) {
				//查询类目
				ForestDO forest = baseForestManager.get(forestBrandTemp.getForestId());
				if (null != forest && AzerothConstants.ItemForest.NORMAL == forest.getStatus()) {
					forestList.add(forest);
				}
			}
		}
		return forestList;
	}

	/**
	 * 移除重复的品牌
	 * @param itemForestBrandList
	 * @return
	 */
	private List<ItemForestBrandDO> removeDuplicateBrand(List<ItemForestBrandDO> itemForestBrandList) {
		List<ItemForestBrandDO> listWithoutDup = new ArrayList<ItemForestBrandDO>();
		for(ItemForestBrandDO itemForestBrandDO:itemForestBrandList) {
			boolean isDup = false;
			for (ItemForestBrandDO brandDOWithoutDup:listWithoutDup)
			if (itemForestBrandDO.getBrandId() == brandDOWithoutDup.getBrandId()) {
				isDup = true;
				break;
			}
			if (!isDup) {
				listWithoutDup.add(itemForestBrandDO);
			}
		}
		return listWithoutDup;
	}
}
